package com.tom.jmgd.util;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {

//    public static String test(Map<String,String> map) throws Exception {
//        String result = "";
//        CloseableHttpClient client = null;
//        CloseableHttpResponse response = null;
//        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
//                .setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
//        client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
//        // client = HttpClients.createDefault();
//        URIBuilder uriBuilder = new URIBuilder("http://202.175.59.29:10443/gwinternet/app-svc/api/v1/refund/initRefund");
//        //URIBuilder uriBuilder = new URIBuilder("http://202.175.59.29:10443/gwinternet/app-svc/api/v1/order");
//
//        HttpPost httpPost = new HttpPost(uriBuilder.build());
//        httpPost.setHeader("Connection", "Keep-Alive");
//        httpPost.setHeader("Charset", "UTF-8");
//        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//
//
////            map.put("amount", "200");
////            map.put("currency", "MOP");
////            map.put("merchantId", "011901200001001");
////            map.put("channel", "ICBCOnlinePosOrder");
////            map.put("merchantOrderId", "southmax892");
////            map.put("merchantTid", "00000001");
////            map.put("returnUrl", "https://apptest.southmax.com.cn/paidSuccess?orderNo=southmax892");
////            map.put("timeout", "300");
////            map.put("notifyUrl", "https://apptest.southmax.com.cn/appt/billing/interface/icbcCallBack?episodeNo=S201911140002&relatedId=503&userId=503&hospId=1");
////            map.put("sign", "6a75e58f8521f9dfce4305b268d63bf0");
//
//
//
//
//        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        while (it.hasNext()) {
//            Map.Entry<String, String> entry = it.next();
//            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
//            params.add(pair);
//        }
//        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//        try {
//            response = client.execute(httpPost);
//            if (response != null) {
//                HttpEntity resEntity = response.getEntity();
//                if (resEntity != null) {
//                    result = EntityUtils.toString(resEntity, "UTF-8");
//                }
//            }
//        } catch (ClientProtocolException e) {
//            throw new RuntimeException("创建连接失败" + e);
//        } catch (IOException e) {
//            throw new RuntimeException("创建连接失败" + e);
//        }
//        return result;
//    }


    //--------------------GET 请求-----------------------
    public static String getRequest(String url, Map<String, String> params) throws IOException {
//        if (StringUtils.isBlank(url)) {
//            throw new MsgException(ResultEnum.URL_EMPTY);
//        }
        StringBuilder sb = new StringBuilder();
        String strUrl = url;
        sb.append(url);
        if (params != null && params.size() > 0) {
            sb.append("?");
            params.forEach((s, s2) -> {
                sb.append(s).append("=").append(s2).append("&");
            });
            strUrl = sb.substring(0, sb.length() - 1);
        }
        return getRequest(strUrl);
    }

    public static String getRequest(String url, String params) throws IOException {
        return getRequest(url + "?" + params);
    }

    public static String getRequest(String url) throws IOException {
        //开启链接
        URLConnection connection = getConnection(url);
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> map = connection.getHeaderFields();
        // 定义 BufferedReader输入流来读取URL的响应
        String response = readResponse(connection);
        return response;
    }

    //--------------------POST 请求-----------------------

    public static String postRequest(String url, Map<String, String> params) throws IOException {
        StringBuilder sb = new StringBuilder();
        String param = "";
        if (params != null && params.size() > 0) {
            params.forEach((s, s2) -> {
                sb.append(s).append("=").append(s2).append("&");
            });
            param = sb.substring(0, sb.length() - 1);
        }
        return postRequest(url, param);
    }

    public static String postRequest(String url, String param) throws IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        URLConnection conn = getConnection(url);
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        OutputStream outputStream = conn.getOutputStream();
        out = new PrintWriter(outputStream);
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        String response = readResponse(conn);
        out.close();
        outputStream.close();
        return response;
    }


//    public static String postRequest2(String url, Map<String, String> map) throws Exception {
//        String result = "";
//        CloseableHttpClient client = null;
//        CloseableHttpResponse response = null;
//        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
//                .setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
//        client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
//        // client = HttpClients.createDefault();
//        //URIBuilder uriBuilder = new URIBuilder("http://202.175.59.29:10443/gwinternet/app-svc/api/v1/refund/initRefund");
//        URIBuilder uriBuilder = new URIBuilder(url);
//
//        HttpPost httpPost = new HttpPost(uriBuilder.build());
//        httpPost.setHeader("Connection", "Keep-Alive");
//        httpPost.setHeader("Charset", "UTF-8");
//        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
////        Map<String,String> map= new HashMap<>();
//////            map.put("currency", "MOP");
//////            map.put("merchantId", "011901200001001");
//////            map.put("merchantOrderId", "southmax881");
//////            map.put("merchantRefundOrderId", "southmax884");
//////            map.put("notifyUrl", "https://apptest.southmax.com.cn/appt/billing/interface/icbcRefundCallBack");
//////            map.put("originAmount", "200");
//////            map.put("refundAmount", "200");
//////            map.put("sign", "9119086a2e2a8a1a045fc7191a497e25");
////
////        map.put("amount", "200");
////        map.put("currency", "MOP");
////        map.put("merchantId", "011901200001001");
////        map.put("channel", "ICBCOnlinePosOrder");
////        map.put("merchantOrderId", "southmax892");
////        map.put("merchantTid", "00000001");
////        map.put("returnUrl", "https://apptest.southmax.com.cn/paidSuccess?orderNo=southmax892");
////        map.put("timeout", "300");
////        map.put("notifyUrl", "https://apptest.southmax.com.cn/appt/billing/interface/icbcCallBack?episodeNo=S201911140002&relatedId=503&userId=503&hospId=1");
////        map.put("sign", "6a75e58f8521f9dfce4305b268d63bf0");
//
//
//        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
//        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        while (it.hasNext()) {
//            Map.Entry<String, String> entry = it.next();
//            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
//            params.add(pair);
//        }
//        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//        try {
//            response = client.execute(httpPost);
//            if (response != null) {
//                HttpEntity resEntity = response.getEntity();
//                if (resEntity != null) {
//                    result = EntityUtils.toString(resEntity, "UTF-8");
//                }
//            }
//        } catch (ClientProtocolException e) {
//            throw new RuntimeException("创建连接失败" + e);
//        } catch (IOException e) {
//            throw new RuntimeException("创建连接失败" + e);
//        }
//        return result;
//    }

    //-------------------私有方法-----------------

    /**
     * 获取http 链接
     *
     * @param url
     * @return
     * @throws IOException
     */
    private static URLConnection getConnection(String url) throws IOException {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        return conn;
    }

    /**
     * 读取返回信息
     *
     * @param connection
     * @return
     * @throws IOException
     */
    private static String readResponse(URLConnection connection) throws IOException {
        StringBuilder result = new StringBuilder();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader in = new BufferedReader(inputStreamReader);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line).append("\n");
        }
        in.close();
        inputStreamReader.close();
        inputStream.close();
        return result.toString();
    }

    /**
     * http请求get,post整合方式
     * 使用httpclient发送请求,JSONObject作为post请求的参数,方便一些以json对象作为参数和返回对象的请求方法调用
     *
     * @param url
     * @param jsonParam     post参数(JSONObject类型)
     * @param requestMethod GET/POST
     * @return JSONObject对象
     * @throws Exception
     */
//    public static JSONObject httpRequest(String url, JSONObject jsonParam, String requestMethod) throws Exception {
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpGet get = null;
//        HttpPost post = null;
//        JSONObject jsonObject = null;
//        CloseableHttpResponse response = null;
//        try {
//            if ("GET".equalsIgnoreCase(requestMethod)) {
//                get = new HttpGet(url);
//                response = httpclient.execute(get);
//            } else if ("POST".equalsIgnoreCase(requestMethod)) {
//                post = new HttpPost(url);
//                //设置参数
//                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
//                entity.setContentEncoding("UTF-8");
//                entity.setContentType("application/json");
//                post.setEntity(entity);
//                response = httpclient.execute(post);
//            }
//            HttpEntity responseEntity = response.getEntity();
//            String responseContent = EntityUtils.toString(responseEntity, "UTF-8");
//            System.out.println("返回" + responseContent);
//            jsonObject = new JSONObject(responseContent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            // 关闭连接,释放资源
//            try {
//                response.close();
//                httpclient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return jsonObject;
//    }
//
//    /**
//     * 上传图片post请求指定url
//     *
//     * @param url
//     * @return
//     * @throws ClientProtocolException
//     * @throws IOException
//     */
//    public static JSONObject httpPostUploadFile(String url) throws ClientProtocolException, IOException {
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        CloseableHttpResponse httpResponse = null;
//        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
//        HttpPost httpPost = new HttpPost(url);
//        httpPost.setConfig(requestConfig);
//        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//        //multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
//        JSONObject jsonObject = null;
//
//        try {
//            File file = new File("E:\\logo.png");
//
//            multipartEntityBuilder.addBinaryBody("buffer", file, ContentType.MULTIPART_FORM_DATA,
//                    //ContentType.create("image/png"),
//                    "logo.png");
//            //当设置了setSocketTimeout参数后，以下代码上传PDF不能成功，将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
//            //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
//            //multipartEntityBuilder.addBinaryBody("file",file);
//            //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
//            //multipartEntityBuilder.addTextBody("comment", "this is comment");
//            HttpEntity httpEntity = multipartEntityBuilder.build();
//            httpPost.setEntity(httpEntity);
//
//            httpResponse = httpClient.execute(httpPost);
//            HttpEntity responseEntity = httpResponse.getEntity();
//            int statusCode = httpResponse.getStatusLine().getStatusCode();
//            if (statusCode == 200) {
//                String responseContent = EntityUtils.toString(responseEntity, "UTF-8");
//                System.out.println(responseContent);
//                jsonObject = new JSONObject(responseContent);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            httpClient.close();
//            if (httpResponse != null) {
//                httpResponse.close();
//            }
//        }
//        return jsonObject;
//    }
}
